<template>
  <div class="log">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>日志</h3>
        </div>
      </template>
      <div id="log" class="log-container">
        <pre>{{ log }}</pre>
      </div>
    </el-card>
  </div>
</template>

<style lang="less">
.log {
  .log-container {
    height: 480px;
    overflow: scroll;
    color: #ffffff;
    background-color: #181818;

    pre {
      padding: 0 20px;
    }
  }
}
</style>

<script setup lang="ts">
import { nextTick, onBeforeMount, onBeforeUnmount, onMounted, ref } from 'vue'
import { backendService } from '@/service/BackendService'
import { CircularBuffer } from '@/service/CircularBufferService'

const log = ref<string>('')
const bottomEnd = ref<boolean>(true)
const logBuffer = new CircularBuffer(2048)
const ctrl = new AbortController()
let logDom: any

const handleScroll = () => {
  if (logDom) {
    bottomEnd.value = logDom.scrollTop + logDom.clientHeight >= logDom.scrollHeight;
  }
}

onBeforeMount(() => {
  backendService.sse(
    '/api/log',
    (event: any) => {
      logBuffer.add(event.data || '\n')
      log.value = logBuffer.getBuffer().join('')
      nextTick(()=>{
        if (logDom && bottomEnd.value) {
          logDom.scrollTop = logDom.scrollHeight
        }
      })
    },
    ctrl
  )
})

onMounted(() => {
  logDom = document.getElementById('log')
  if (logDom) {
    logDom.addEventListener('scroll', handleScroll)
  }
})

onBeforeUnmount(() => {
  ctrl.abort()
  if (logDom) {
    logDom.removeEventListener('scroll', handleScroll)
  }
})
</script>
